package com.ruiyi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.ruiyi.common.Constants;
import com.ruiyi.common.Result;
import com.ruiyi.utils.SendEmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/email")
public class EmailCodeController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/send.do")
    @ResponseBody
    public Result sendCode(String username,String email){/*获取 用户邮箱*/
        Result result = new Result();
        /*0验证该邮箱是否 存在可用验证码*/
        String redisKey = username+"-"+email;
        Boolean hasKey = stringRedisTemplate.hasKey(redisKey);
        Long time = stringRedisTemplate.getExpire(redisKey);
        if (hasKey){
            return new Result(-1,"请"+time+"秒后重试");
        }
        /*1生成随机验证码*/
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 50,4,0);
        String code = lineCaptcha.getCode();
        /*2发送邮件*/
        Thread thread = new Thread(new SendEmailUtil(email,code),redisKey);
        thread.start();
        /*3验证码 存入 redis 180s*/
        stringRedisTemplate.opsForValue().set(redisKey,code,180, TimeUnit.SECONDS);
        return result;
    }
}
